package fr.toto.menuitem;

import java.nio.file.Path;

import javax.swing.JMenu;
import javax.swing.JMenuItem;

import com.kokotchy.betaSeriesAPI.model.Episode;


public class MyMenu extends JMenu {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1839709688672145386L;

	MyMenu mm = null;

	public MyMenu(String string) {
		super(string);
	}

	public void add(Episode ep, Path p) {
		if (p.getNameCount() > 1) {
			if (mm != null
					&& mm.getText().equalsIgnoreCase(p.getName(0).toString())) {
				mm.add(ep, p.subpath(1, p.getNameCount()));
			} else {
				mm = new MyMenu(p.getName(0).toString());
				this.add(mm);
				mm.add(ep, p.subpath(1, p.getNameCount()));
			}
		} else {
			this.add(new MyMenuItem(ep, p));
		}

	}
	
	public boolean optimized() {
		boolean optimum = true;
		for (int i = this.getItemCount() - 1; i>=0 ; i--) {
			JMenuItem comp = this.getItem(i);
			if (comp instanceof MyMenu) {
				MyMenu mm = (MyMenu) comp;
				if(mm.optimized() || this.getItemCount() == 1) {
					for(int j = mm.getItemCount() - 1; j>=0; j--) {
						this.insert(mm.getItem(j),i);
					}
					this.remove(mm);
				} else {
					optimum = false;
				}
			}
		}
		return (optimum && this.getItemCount() < 3);
	}


}
